<?php

use console\db\channels\TransferTableMigration;
use yii\helpers\HtmlPurifier;
use yii\db\Query;

/**
 * 泰山号资讯内容转移
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m300010_000002_t_cms_article_data_append extends TransferTableMigration {

    /**
     * @inheritdoc
     */
    public $sourceDb = 'olddb';

    /**
     * @inheritdoc
     */
    public $beforeTruncateTargetTable = false;

    /**
     * @inheritdoc
     */
    public function buildQuery() {
        return (new Query())->from('{{%' . $this->sourceTable . '}}')->where(['>=', 'article_id', 5397]);
    }

    /**
     * @inheritdoc
     */
    public function safeDown() {
        $this->delete('{{%' . $this->targetTable . '}}', ['>=', 'article_id', 5398]);
    }

    /**
     * @inheritdoc
     */
    public function validateTransfer(&$data) {
        if (!parent::validateTransfer($data)) {
            return false;
        }
        if ($data['article_id'] == 5397) {
            $data['article_id'] = 5400;
        }
        $exists = (new Query)->from('{{%cms_article}}')->where([
            'id' => $data['article_id']
        ])->exists();
        if ($exists) {
            return true;
        }
        return false;
    }

    /**
     * @inheritdoc
     */
    public function getTransferOptions() {
        return [
            'table' => [
                'cms_article_data' => 'ts_article_data',
            ],
            'columns' => [
                'article_id',
                'body' => function($data) {
                    return HtmlPurifier::process($data['body'], [
                        'HTML.Allowed' => 'div,p,img[src],table,tr,td',
                        'AutoFormat.RemoveEmpty' => true
                    ]);
                },
            ]
        ];
    }

}
